package name.panitz.mobile;
import javax.microedition.lcdui.*;
import java.util.*;
public class TrainFroggerMidlet extends GameMidlet{
  final static int TRACK_HEIGHT = 33;
  int track_number = 5;

  final Random random=new Random();

  double maxSpeed=5.5;
  double minSpeed=1;
  int minSpace=40;
  int maxSpace=80;

  Image[] trainIcons =
   {ImageObject.load("/e120s.png"),ImageObject.load("/e182s.png")
   ,ImageObject.load("/e103s.png"),ImageObject.load("/e120s.png")
   ,ImageObject.load("/e140s.png")};

  MovableObject frog=new ImageObject(0,0,0,0,"/frog.png");

  public TrainFroggerMidlet() {
    myCanvas=new MyCanvas(){
      protected void keyPressed(int keyCode){
        if (keyCode==Canvas.KEY_NUM4) frog.dX-=1;
        if (keyCode==Canvas.KEY_NUM6) frog.dX+=1;
        if (keyCode==Canvas.KEY_NUM2) frog.y-=TRACK_HEIGHT;
        if (keyCode==Canvas.KEY_NUM8) frog.y+=TRACK_HEIGHT;
        if (keyCode==Canvas.KEY_NUM0) {frog.dY=0;frog.dX=0;}
      } 
    };
    initDisplay();

    track_number
      = (myCanvas.getHeight()-2*TRACK_HEIGHT)/TRACK_HEIGHT;

    resetFrog();
    mos.addElement(frog);

    fillings  = new int[track_number];
    for (int i=0;i<track_number;i++) addTrains(i);
  }

  int [] fillings;
  void addTrains(int trackNr){
    double speed = random.nextDouble()*maxSpeed*2+minSpeed;
    if(speed>maxSpeed+minSpeed)
       speed = speed-(2*maxSpeed+minSpeed);

    int filled = 0;
    while (filled < myCanvas.getWidth()+300){
      Image icon = trainIcons[random.nextInt(trainIcons.length)];
      final int x = speed<0?filled:-filled;
      final MovableObject train
       =new ImageObject
          (filled
          ,myCanvas.getHeight()-(2+trackNr)*TRACK_HEIGHT
          ,speed ,0,icon);
      mos.addElement(train);
      filled 
       = filled+train.width+random.nextInt(maxSpace)+minSpace;
    }
    fillings[trackNr]=filled;
  }

  int getFill(int y){
    int ind=(myCanvas.getHeight()-2*TRACK_HEIGHT-y)/TRACK_HEIGHT;
    return fillings[ind];
  }

  void resetFrog(){
    frog.x=myCanvas.getWidth()/2;
    frog.y=myCanvas.getHeight()-frog.height;
    frog.dX=0;
    frog.dY=0;
  }

  public void doOnTic(){
    super.doOnTic();
    for (Enumeration e = mos.elements();e.hasMoreElements();){
      MovableObject go=(MovableObject)e.nextElement();	
      if (go!=frog){
        if (go.touches(frog)) resetFrog();

        if (go.dX> 0 && go.x > myCanvas.getWidth())
          go.x-=getFill(go.y);
        else if (go.dX< 0&& go.x+go.width < 0) 
          go.x+=getFill(go.y);
      }
    }
  }
}

